/*
 * AnimSprite.cpp
 *
 *  Created on: Aug 2, 2009
 *      Author: kurt
 */

#include "AnimSprite.h"
#include "DrawingCanvas.h"
#include <psprtc.h>
using namespace std;
using namespace objdraw;

AnimSprite::~AnimSprite() 
{
	if(auto_delete && image != NULL)
	{
		image->removeFromCanvas();
		image->Delete();
		image = NULL;
	}
}
AnimSprite::AnimSprite() 
{
	start = Location(0,0);
	end = Location(0,0);
	color = Color(0,0,0);
	hidden = false;
	canvas = NULL;
	image = NULL;
	imagedata = NULL;
	auto_delete = false;
	tileStart = tileStart = Location(0,0);
	frameWidth = frameHeight = 0.0f;
	frameStart = Location(0,0);
	currentFrame = 0;
	animating = false;
	loop = true;
	reof = false;
	cFrameIndex = 0;
	speed = 0.0f;
	sceRtcGetCurrentTick( &tickLast );
	tickResolution = sceRtcGetTickResolution();
}
AnimSprite::AnimSprite(Image * img, DrawingCanvas * c, bool auto_del)
{
	start = Location(0,0);
	end = Location(0,0);
	if(img != NULL)
		end = Location(img->getX() + img->getWidth(),img->getY() + img->getHeight());
	color = Color(0,0,0);
	hidden = false;
	canvas = c;
	image = img;
	imagedata = image->image;
	auto_delete = auto_del;
	tileStart = Location(0,0);
	tileEnd = end;
	frameWidth = frameHeight = 0.0f;
	frameStart = Location(0,0);
	currentFrame = 0;
	animating = false;
	cFrameIndex = 0;
	speed = 0.0f;
	loop = true;
	reof = false;
	sceRtcGetCurrentTick( &tickLast );
	tickResolution = sceRtcGetTickResolution();
	if(canvas != NULL)
		canvas->getCanvasContent().addDrawable(this);
}
void AnimSprite::setAniFrames(uint start, uint end)
{
	aniFrames.clear();
	for(uint i = start; i < end+1; i++)
		aniFrames.push_back(i);
	cFrameIndex = 0;
	if(aniFrames.size() > 0) 
		setFrame(aniFrames.at(0));
	else 
		setFrame(0);
}
void AnimSprite::update()
{
	if(!animating) return;
	
	u64 tickNow;
	sceRtcGetCurrentTick( &tickNow );
	
	if( ((tickNow - tickLast)/((float)tickResolution)) >= speed )
	{
		tickLast = tickNow;
		if(cFrameIndex+1 >= aniFrames.size())
		{
			if(loop)
				cFrameIndex = 0;
			else
			{
				animating = false;
				if(reof) rewind();
			}
		}
		else
			cFrameIndex++;
		setFrame(aniFrames.at(cFrameIndex));
	}
}
